package com.pet_service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet_service.entity.*;
import com.pet_service.mapper.PermissionMapper;
import com.pet_service.mapper.RoleMapper;
import com.pet_service.mapper.UserMapper;
import com.pet_service.mapper.UserRoleMapper;
import com.pet_service.result.Result;
import com.pet_service.service.UserService;
import com.pet_service.vo.GrantRoleBean;
import com.pet_service.vo.PasswordBean;
import com.pet_service.vo.UserWithPetsVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 邹全伸
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-09-20 09:18:18
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;


    @Override
    public String getUserAuthorityInfo(Integer userId) {
        //1.创建拼接字符串StringBuffer
        StringBuffer buffer = new StringBuffer();

        //2.根据userId查询这个用户拥有的角色
        List<Role> roleList = roleMapper.selectRoleByUserId(userId);
        // log.info("用户ID为{},拥有角色:{}",userId,roleList);
        if(Objects.nonNull(roleList)){
            String roleStr= roleList.stream().map(role->"ROLE_"+role.getRole_code()).
                    collect(Collectors.joining(","));
            //将roleStr追加到buffer中 ROLE_common,ROLE_test
            buffer.append(roleStr);
        }

        //3.准备一个set集合，存储所有的权限名称
        Set<String> menuSet =new LinkedHashSet<>();
        List<Permission> sysMenuSet = permissionMapper.selectPermissionByRoleId(roleList);
        // log.info("用户id为{}，拥有权限:{}",userId,sysMenuSet);
        if(Objects.nonNull(sysMenuSet)){
            for(Permission permission:sysMenuSet){
                String perms = permission.getPerms();
                if(StrUtil.isNotEmpty(perms)){
                    menuSet.add(perms);
                }
            }
        }
        //log.info("menuSet={}",menuSet);
        if(menuSet.size()>0){
            buffer.append(",");
            String menuStr = menuSet.stream().collect(Collectors.joining(","));
            buffer.append(menuStr);
        }

        log.info("userId为{}拥有角色和权限字符串为:{}",userId,buffer.toString());
        return buffer.toString();
    }

    @Override
    public Result checkUserName(String username) {
        long count = userMapper.checkUserName(username);
        return count>0?Result.fail("此用户名已被使用!"):Result.ok("此用户名可以使用！");
    }

    @Override
    public Result checkUserPhone(String userPhone) {
        long count = userMapper.checkUserPhone(userPhone);
        return count>0?Result.fail("此手机号码已被使用!"):Result.ok("此手机号码可以使用！");
    }

    @Transactional
    @Override
    public Result removeByUserIdList(List<Integer> ids) {
        try{
            //去 user_role中间表中删除 指定uid的数据（物理删除）
            userRoleMapper.deleteByUserIdList(ids);
            //再去 use表中删除这个用户信息（逻辑删除）直接调用mybatis-plus提供的方法
            userMapper.deleteByIds(ids);
            return Result.ok("删除成功！");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
    }

    @Transactional
    @Override
    public Result grantRole(GrantRoleBean grantRoleBean) {
        log.info("grantRoleBean={}",grantRoleBean);
        //先删除这个用户角色delete from  user_role  where  uid =?  (物理删除不是逻辑删除)
        userRoleMapper.deleteByUserId(grantRoleBean.getUser_id());
        //批量插入
        List<UserRole> list=new ArrayList<>();
        if(Objects.nonNull(grantRoleBean.getRoleIds())){
            for (Integer roleId : grantRoleBean.getRoleIds()) {
                log.info("uid={}",grantRoleBean.getUser_id());
                UserRole userRole=new UserRole();
                userRole.setUser_id(grantRoleBean.getUser_id());
                userRole.setRole_id(roleId);
                list.add(userRole);
            }
        }
        userRoleMapper.insert(list);
        return Result.ok("角色分配成功!");
    }

    @Override
    public Result updateBaseInfo(User user) {
        int n =userMapper.updateBaseInfo(user);
        return n>0?Result.ok("更新成功!"):Result.fail("更新失败!");
    }

    @Override
    public Result updatePassword(PasswordBean passwordBean) {
        User user = new User();
        user.setId(passwordBean.getId());
        user.setPassword(new BCryptPasswordEncoder().encode(passwordBean.getNewPassword()));
        int n = userMapper.updatePassword(user);
        return n>0?Result.ok("密码修改成功!"):Result.fail("密码修改失败!");
    }

    @Override
    public IPage<User> pageByRoleCode(Page<User> page, String roleCode, String query) {
        Page<User> resultPage = new Page<>(page.getCurrent(), page.getSize());

        List<User> list = userMapper.selectUsersByRoleCode(roleCode, query);
        Long count = userMapper.selectUsersByRoleCodeCount(roleCode, query);

        resultPage.setRecords(list);
        resultPage.setTotal(count);

        return resultPage;
    }

    //查询用户的宠物信息
    @Override
    public UserWithPetsVO getUserWithPets(Integer userId) {
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        List<PetInfo> petList = userMapper.selectPetsByUserId(userId);

        return new UserWithPetsVO(user, petList);
    }
}




